package helper

import (
	"crypto/md5"
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
)

type UserClaim struct {
	Identity string `json:"identity"`
	Email    string `json:"email"`
	jwt.StandardClaims
}

func GetMd5(s string) string {
	return fmt.Sprintf("%x", md5.Sum([]byte(s)))
}

func GenToken(identity, email string) (string, error) {
	uc := &UserClaim{
		Identity: identity,
		Email:    email,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Second * time.Duration(60000)).Unix(),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, uc)

	tokenString, err := token.SignedString(myJwtKey()) // 假设 myJwtKey() 是获取密钥的函数
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

// https://juejin.cn/post/7137156362651303966
// fixed key is of invalid type error
func myJwtKey() []byte {
	return []byte("go-im")
}

func AnalyseToken(tokenString string) (*UserClaim, error) {
	uc := new(UserClaim)
	claims, err := jwt.ParseWithClaims(tokenString, uc, func(token *jwt.Token) (any, error) {
		return myJwtKey(), nil
	})
	if err != nil {
		return nil, err
	}

	if !claims.Valid {
		return nil, fmt.Errorf("analyse token error: %v", err)
	}

	return uc, nil
}
